import React, {Component} from 'react';
import {ShoppingOutlined,ShoppingCartOutlined} from "@ant-design/icons";
import {withRouter} from "react-router-dom";
import {Popover,Badge} from 'antd'
import {PubSub} from 'pubsub-js'
import {connect} from "react-redux";
import {setGood} from "../../../redux/actions/shopCar";
import './index.less'
import {MiniCar} from "./MiniCar";
import Notice from "../../Notice";


class ShopIcon extends Component {
    showWhat = () => {
        if(this.props.carList.length === 0){
            return (
                <div className='empty'>
                    <div className='carIcon'>
                        <ShoppingCartOutlined />
                    </div>
                    <div className='msgTitle'>
                        您的购物车为空或未登录！
                    </div>
                    <div className='msgDesc'>
                        赶快去购物吧！
                    </div>
                </div>
            )
        }else{
            return (
                <MiniCar carList={this.props.carList}/>
            )
        }
    }
    goCar = () => {
        if(sessionStorage.getItem('userId')){
            this.props.history.push('/car')
        }else{
            Notice('info','提示','请您先登录后在进入购物车页面')
        }
    }
    getCount = (arr) => {
        let count = 0
        if(arr.length !== 0) {
            arr.forEach(item => {
                count += item.gcount * 1
            })
        }
        return count
    }
    render() {
        return (
            <>
                <Popover placement='bottomRight' content={this.showWhat()}>
                    <Badge count={this.getCount(this.props.carList)} className='shopCar' size='small'>
                    <ShoppingOutlined onClick={this.goCar}/>
                    </Badge>
                </Popover>
            </>
        );
    }
    componentDidMount() {
        let uid = sessionStorage.getItem('userId')
        if(uid){
            this.props.setGood(uid)
        }
        this.token = PubSub.subscribe('userLogin',async (_,userid) => {
            this.props.setGood(userid)
        })
    }
    //发起ajax请求并设置redux的值
    componentWillUnmount() {
        //组件卸载时取消事件订阅
        PubSub.unsubscribe(this.token)
    }
}
export default withRouter(
    connect(
        state => ({carList: state.carList}),
        {
            setGood
        }
    )(ShopIcon)
)
